﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using OnLineExam.Model;
using OnLineExam.BLL;
using System.DirectoryServices;

namespace OnLineExam.Web
{
    public partial class LoginAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
			 

			if (Request.QueryString["type"] == "out")
            {
                FormsAuthentication.SignOut();
            }
            else
            {
                string uname = Request.Params["txtUserName"];
                string upass = Request.Params["txtUserPass"];
                login(uname, upass);
            }
        }

        void login(string username,string userpass)
        {
           

            try
            {
                #region
                //string usersId = username;
                //string pwdMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(userpass, "MD5").ToString();


				var userEntity = DBLogin(username, userpass);
				if (userEntity == null)
				{
					userEntity=ADLogin(username, userpass);
				}
				if (userEntity != null)
				{
					UserInfo(userEntity.UserID, userEntity.Role.RoleName);

					Response.Write(userEntity.Role.RoleName);


				}
                else
                {
                    Response.Write("无此用户。");
                }
                #endregion
            }
            catch (Exception ex)
            {
                var logger = NLog.LogManager.GetCurrentClassLogger();

                logger.Error(ex, "login:"+new Data.OnlineExamEntities().Database.Connection.ConnectionString);
                Response.Write(ex.Message);
               
                 
            }
        }
	 

		private Data.Users DBLogin(string username,string pwd) {
			string pwdMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5").ToString();

            using (var ctx=new Data.OnlineExamEntities())
            {
                var user = ctx.Users.FirstOrDefault(s=>s.UserID==username && s.UserPwd==pwdMd5);

                if(user!=null)
                user.Role = ctx.Role.First(s=>s.RoleId==user.RoleId);
                return user;

            } 
		}
		private void CreateUserByAdLogin(Data.Users user) {
			try
			{
                using (var ctx = new Data.OnlineExamEntities())
                {
                     ctx.Users.Add(user);
                    ;

                }
                
			}
			catch (Exception)
			{

				 
			}
		}

		private  Data.Users ADLogin(string username, string pwd) {
			string domain = "sf"; 

			string adPath = "LDAP://10.63.7.100/dc=sf,dc=com";

			LdapAuthentication adAuth = new LdapAuthentication(adPath);
			SearchResult result = (SearchResult)adAuth.Authenticated(domain, username, pwd);

			if (null != result)
			{
				//GetMailAddressFromAD(username, adPath);
				string _path = result.Path;
				string _filterAttribute = (string)result.Properties["cn"][0];

				var role = RoleManager.GetRole("学生");

                string pwdMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5").ToString();
                var user= new Data.Users {
					UserID= username, UserName=_filterAttribute, CourseID=0, Depcode="", DepID=0, RoleId= role.RoleId, UserPwd= pwdMd5, u_type="ad"
				};
				
				CreateUserByAdLogin(user);
                user.Role = new Data.Role { RoleId = role.RoleId, RoleName = role.RoleName };
                return user;
			}
			else
			{
				return null;
			}
		}
		void UserInfo(string username, string userinfo)
        {
            // FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, true, 60);
            FormsAuthenticationTicket t1 = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddHours(2), false, userinfo);
            string encryptedTicket = FormsAuthentication.Encrypt(t1);//加密
            HttpCookie c1 = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            c1.Expires = t1.Expiration;
            Response.Cookies.Add(c1);
        }
		 
    }
}